<template>
  <page-header-wrapper>
    <a-card>
      <AnypaySearchForm :searchFunc="searchFunc" :resetFunc="resetSearch">
        <anypay-text-up v-model:value="searchData.studentNo" placeholder="学号" />
        <anypay-text-up v-model:value="searchData.name" placeholder="姓名" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData.grade" placeholder="年级">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="2023">2023级</a-select-option>
            <a-select-option value="2022">2022级</a-select-option>
          </a-select>
        </a-form-item>
      </AnypaySearchForm>

      <AnypayTable
        ref="itemTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="searchData"
        rowKey="id"
        @btnLoadClose="btnLoading = false"
      >
        <template #topBtnSlot>
          <div>
            <a-button type="primary" class="mg-b-30" @click="addItem">
              <plus-outlined /> 新增学生
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'gender'">
            {{ record.gender === 'M' ? '男' : '女' }}
          </template>
          <template v-if="column.key === 'grade'">
            <a-tag>
              {{ record.grade === '2023' ? '2023级' : '' }}
              {{ record.grade === '2022' ? '2022级' : '' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag>
              {{ record.status === 'active' ? '在读' : '' }}
              {{ record.status === 'graduated' ? '已毕业' : '' }}
              {{ record.status === 'suspended' ? '休学' : '' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'op'">
            <AnypayTableColumns>
              <a-button type="link" @click="editItem(record)">编辑</a-button>
              <a-button type="link" @click="viewItem(record)">查看</a-button>
              <a-button type="link" style="color: red" @click="deleteItem(record.id)">删除</a-button>
            </AnypayTableColumns>
          </template>
        </template>
      </AnypayTable>
    </a-card>

    <StudentAddOrEditDrawer
      ref="addOrEditDrawRef"
      :callbackFunc="searchFunc"
    />

    <StudentDetailDrawer ref="detailDrawerRef" />
  </page-header-wrapper>
</template>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { apiStudentFetchList, apiStudentDelete } from "./api";
import StudentDetailDrawer from "./Detail.vue";
import StudentAddOrEditDrawer from "./AddOrEdit.vue";

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties;

// 搜索条件
const searchData = reactive<{
  studentNo: string;
  name: string;
  grade: string;
}>({
  studentNo: "",
  name: "",
  grade: "",
});

// 表格列定义
const tableColumns = reactive([
  { key: "id", title: "Id", dataIndex: "id" },
  { key: "studentNo", title: "学号", dataIndex: "studentNo" },
  { key: "name", title: "姓名", dataIndex: "name" },
  { key: "gender", title: "Gender", dataIndex: "gender" },
  { key: "age", title: "Age", dataIndex: "age" },
  { key: "className", title: "ClassName", dataIndex: "className" },
  { key: "major", title: "Major", dataIndex: "major" },
  { key: "grade", title: "年级", dataIndex: "grade" },
  { key: "phone", title: "Phone", dataIndex: "phone" },
  { key: "email", title: "Email", dataIndex: "email" },
  { key: "address", title: "Address", dataIndex: "address" },
  { key: "avatar", title: "Avatar", dataIndex: "avatar" },
  { key: "enrollmentDate", title: "EnrollmentDate", dataIndex: "enrollmentDate" },
  { key: "status", title: "Status", dataIndex: "status" },
  { key: "remark", title: "Remark", dataIndex: "remark" },
  { key: "createdAt", title: "CreatedAt", dataIndex: "createdAt" },
  { key: "updatedAt", title: "UpdatedAt", dataIndex: "updatedAt" },
  { key: "op", title: "操作", fixed: "right", align: "center" },
]);

// 组件引用
const itemTable = ref();
const addOrEditDrawRef = ref();
const detailDrawerRef = ref();
const btnLoading = ref(false);

// 表格数据加载
async function reqTableDataFunc(params: any) {
  try {
    const ret = await apiStudentFetchList(params);
    return ret.data;
  } catch (error) {
    console.error('Failed to fetch data list:', error);
    return { records: [], total: 0 };
  }
}

// 搜索和重置
function searchFunc() {
  itemTable.value?.refTable(true);
}

function resetSearch() {
  searchData.studentNo = "";
  searchData.name = "";
  searchData.grade = "";
  itemTable.value?.refTable(true);
}

// CRUD操作
function addItem() {
  addOrEditDrawRef.value?.show(null);
}

function editItem(item: any) {
  addOrEditDrawRef.value?.show(item);
}

function viewItem(item: any) {
  detailDrawerRef.value?.openDrawer(item);
}

function deleteItem(itemId: number) {
  $infoBox.confirmDanger('确认删除该学生信息？', '', () => {
    apiStudentDelete(itemId).then(() => {
      $infoBox.message.success('删除成功');
      searchFunc();
    });
  });
}
</script>